/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.util.provider;

import utsc.apps.utschedule.classes.Timetable;
import utsc.apps.utschedule.util.database.DatabaseManager;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SearchRecentSuggestionsProvider;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MergeCursor;
import android.net.Uri;
import android.provider.BaseColumns;

/**
 * A custom search provider which provides the search suggestions to both System
 * search and in-app search. It can provide suggestions for {@link Course
 * courses}, {@link Assignment assignments}, and {@link Exam exams}.
 * 
 */
public class SearchProvider extends SearchRecentSuggestionsProvider {

	public static final String TAG="utsc.apps.utschedule.util.provider.SearchProvider";
	public static final String AUTHORITY="utsc.apps.utschedule.util.provider.SearchProvider";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/search");
	public final static int MODE = DATABASE_MODE_QUERIES | DATABASE_MODE_2LINES;
	public static final int COURSES=1;
	public static final int COURSE=6;
	public static final int ASSIGNMENTS=2;
	public static final int ASSIGNMENT=7;
	public static final int EXAMS=3;
	public static final int EXAM=8;
	public static final int ONLINE=9;
	
	public static final int SEARCH_SUGGEST=99;
	public static final int REFRESH_SHORTCUT=100;
	
	private static final UriMatcher _URI_MATCHER =buildUriMatcher();
	
	// MIME types used for searching
    public static final String COURSES_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE +
                                                  "/vnd.utsc.apps.utschedule.courses";
    public static final String COURSE_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE+
            "/vnd.utsc.apps.utschedule.courses";
    public static final String ASSIGNMENTS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE +
            "/vnd.utsc.apps.utschedule.assignments";
    public static final String ASSIGNMENT_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE +
            "/vnd.utsc.apps.utschedule.assignments";
    public static final String EXAMS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE +
            "/vnd.utsc.apps.utschedule.exams";
    public static final String EXAM_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE +
            "/vnd.utsc.apps.utschedule.exams";
    public static final String ONLINE_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE +
            "/vnd.utsc.apps.utschedule.online";

	/**
     * Builds up a UriMatcher for search suggestion and shortcut refresh queries.
     */
    private static UriMatcher buildUriMatcher() {
        UriMatcher matcher =  new UriMatcher(UriMatcher.NO_MATCH);
        matcher.addURI(AUTHORITY, "courses", COURSES);
        matcher.addURI(AUTHORITY, "courses/#", COURSE);
        
        matcher.addURI(AUTHORITY, "assignments", ASSIGNMENTS);
        matcher.addURI(AUTHORITY, "assignments/#", ASSIGNMENT);
        
        matcher.addURI(AUTHORITY, "exams", EXAMS);
        matcher.addURI(AUTHORITY, "exams/#", EXAM);
        
        //matcher.addURI(AUTHORITY, "online", ONLINE);
        matcher.addURI(AUTHORITY, "online/*", ONLINE);
        // to get suggestions...
        matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
        matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);

        /* The following are unused in this implementation, but if we include
         * {@link SearchManager#SUGGEST_COLUMN_SHORTCUT_ID} as a column in our suggestions table, we
         * could expect to receive refresh queries when a shortcutted suggestion is displayed in
         * Quick Search Box, in which case, the following Uris would be provided and we
         * would return a cursor with a single item representing the refreshed suggestion data.
         */
        matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT, REFRESH_SHORTCUT);
        matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", REFRESH_SHORTCUT);
        return matcher;
    }
	
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		switch (_URI_MATCHER.match(uri)) {
		case COURSES:
			return COURSES_MIME_TYPE;
		case COURSE:
			return COURSE_MIME_TYPE;
		case ASSIGNMENTS:
			return ASSIGNMENTS_MIME_TYPE;
		case ASSIGNMENT:
			return ASSIGNMENT_MIME_TYPE;
		case EXAMS:
			return EXAMS_MIME_TYPE;
		case EXAM:
			return EXAM_MIME_TYPE;
		case SEARCH_SUGGEST:
			return SearchManager.SUGGEST_MIME_TYPE;
		case REFRESH_SHORTCUT:
			return SearchManager.SHORTCUT_MIME_TYPE;
		/*case ONLINE:
			return ONLINE_MIME_TYPE;*/
		default:
			throw new IllegalArgumentException("Unknown URL "+uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean onCreate() {
		setupSuggestions(AUTHORITY, MODE);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		  if (selectionArgs == null) {
            throw new IllegalArgumentException(
                "selectionArgs must be provided for the Uri: " + uri);
          }
          return getSuggestions(selectionArgs[0]);
	}

	private Cursor getSuggestions(String query) {
	      String[] columns = new String[] {
	          BaseColumns._ID,
	          SearchManager.SUGGEST_COLUMN_TEXT_1,
	          SearchManager.SUGGEST_COLUMN_TEXT_2,
	          SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
	          SearchManager.SUGGEST_COLUMN_INTENT_DATA,
	          SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,

	          //SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
	          };
	      final DatabaseManager dbManager=DatabaseManager.getInstance(getContext());
	      Timetable t=dbManager.getCurrentActiveTimetable();
	      int timetableID=0;
	      
	      if (t!=null) {
	    	  timetableID=t.get_timetableID();
	      }
	      String[] searchColumns = new String[] {
		          BaseColumns._ID,
		          SearchManager.SUGGEST_COLUMN_TEXT_1,
		          SearchManager.SUGGEST_COLUMN_TEXT_2,
		          SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
		          SearchManager.SUGGEST_COLUMN_INTENT_DATA,
		          SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
		          SearchManager.SUGGEST_COLUMN_QUERY};
	      Cursor suggestions=dbManager.querySuggestionMatches(query, timetableID,columns);
	      MatrixCursor matrixCursor=new MatrixCursor(searchColumns, 1);
	      matrixCursor.addRow(new Object[]{-99,"Search \""+query+"\" online","Search \""+query+"\" on UTSC Intranet",Intent.ACTION_SEARCH,"content://"+SearchProvider.AUTHORITY+"/online/"+query,SearchManager.SUGGEST_NEVER_MAKE_SHORTCUT,query});
	      return new MergeCursor(new Cursor[]{suggestions,matrixCursor});
	}
	
	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		return 0;
	}

}
